import { getDetailsApi } from "@/api/financialManagement/singleOrderApproval/index";
import { message } from "ant-design-vue";
import { clone } from "lodash";
import { reactive, ref, Ref } from "vue";

export default function InitHook(state: { emit: any; searchData: Ref<any> }) {
  const { emit, searchData } = state;
  const formState = ref<any>({
    bizPreOrderShipmentResDto: {},
    bizOrderShipmentQuotation: {},
    bizOrderShipmentCosts: [],
    appendCost: {
      list: [],
      totalPrice: 0,
      type: undefined,
      typeName: ""
    },
    freightCost: {
      list: [],
      totalPrice: 0,
      type: undefined,
      typeName: ""
    },
    addCost: {
      list: [],
      totalPrice: 0,
      type: undefined,
      typeName: ""
    },
    sumTotalPrice: 0
  });
  const loading = ref<boolean>(false);
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "修改送货仓库",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  const drawerOpts = reactive<Base.DrawerOpts>({
    title: "修改送货仓库",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  // 有报价ID
  const init = (id: string, selectNext?: boolean, search?: any) => {
    loading.value = true;
    return getDetailsApi({ id, selectNext: selectNext ? selectNext : false, ...search })
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          if (data) {
            formState.value = data;
            if (!data.addCost) {
              formState.value.addCost = {
                list: [],
                totalPrice: 0,
                type: undefined,
                typeName: ""
              };
            }
            if (!data.appendCost) {
              formState.value.appendCost = {
                list: [],
                totalPrice: 0,
                type: undefined,
                typeName: ""
              };
            }
            if (!data.freightCost) {
              formState.value.freightCost = {
                list: [],
                totalPrice: 0,
                type: undefined,
                typeName: ""
              };
            }
          } else {
            message.info("已经是最后一条数据!");
            emit("submit");
          }
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const search = ref<SingleOrderApproval.SearchParams>(clone(searchData.value()));
  return {
    formState,
    loading,
    dialogOpts,
    drawerOpts,
    init,
    search
  };
}
